package com.javaAdmin.controller;

import cn.hutool.json.JSONUtil;
import com.javaAdmin.model.Admin;
import com.javaAdmin.server.AdminServer;
import com.javaAdmin.util.Result;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Administrator
 */
@RestController
@RequestMapping("/redis")
public class RedisController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private AdminServer adminServer;

    @GetMapping("/add")
    public void add() {
        List<Admin> admins = adminServer.list();
        System.out.println(admins);
        stringRedisTemplate.opsForValue().set("adminList", JSONUtil.toJsonStr(admins),5000);
    }

    @GetMapping("/list")
    public List<Admin> list() {
        String adminsList = stringRedisTemplate.opsForValue().get("adminList");
        System.out.println(adminsList);

        List<Admin> admins = JSONUtil.toList(adminsList, Admin.class);
        for (Admin admin : admins) {
            System.out.println(admin);
        }
        System.out.println(admins);
        return admins;
    }

    @GetMapping("/update")
    public void update() {

        Admin admin = new Admin();
        admin.setId(1);
        admin.setName("admin");
        admin.setPassword("123456");
        admin.setAddress("北京");

        List<Admin> admins = new ArrayList<>();
        admins.add(admin);

        stringRedisTemplate.opsForValue().set("adminList", JSONUtil.toJsonStr(admins));

        System.out.println(admin);
    }

    @GetMapping("/del")
    public void del() {

        boolean rs = stringRedisTemplate.delete("adminList");
        if (rs == true) {
            Result.success();
        } else {
            Result.fail();
        }
    }
}
